package me.chyxion.dao.mybatis.pagination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MySQL Or MariaDB Pagination Query
 * <pre>
 *     select user_name, gender,
 *     from  users
 *     order by birthdate desc, user_id asc
 *     limit 1, 16
 * </pre>
 * @version 0.0.1
 * @since 0.0.1
 * @author chyxion <br />
 * chyxion@163.com <br />
 * Dec 2, 2014 2:49:34 PM
 */
public class DialectMySQL extends DbDialect {
	private static final Logger log = LoggerFactory.getLogger(DialectMySQL.class);

	@Override
	public String getSimplePageSQL(String strSQL, PageParam<?> pageParam) {
		return getPageSQL(strSQL, pageParam, false);
	}

	/**
	 * get page sql
	 * @param strSQL
	 * @param pageParam
	 * @param prepare
	 * @return
	 */
	private String getPageSQL(String strSQL, PageParam<?> pageParam, boolean prepare) {
		Object start, limit;
		if (prepare) {
			start = limit = "?";
		}
		else {
			start = pageParam.getStart();
			limit = pageParam.getLimit();
		}
		StringBuilder sbSQL = 
				new StringBuilder(strSQL)
				.append(" order by ")
				.append(buildOrderBy(pageParam))
				.append(" limit ")
				.append(start)
				.append(", ")
				.append(limit);
		log.debug("Generate Page Query SQL: [{}].", sbSQL);
		return sbSQL.toString();
	}

	/*
	 * (non-Javadoc)
	 * @see me.chyxion.dao.mybatis.pagination.DbDialect#leftWordWrapper()
	 */
	@Override
	public String leftWordWrapper() {
		return "`";
	}

	/*
	 * (non-Javadoc)
	 * @see me.chyxion.dao.mybatis.pagination.DbDialect#rightWordWrapper()
	 */
	@Override
	public String rightWordWrapper() {
		return "`";
	}

	/* (non-Javadoc)
	 * @see me.chyxion.lawnation.dao.mybatis.DbDialect#getPagePreparedStagementSQL(java.lang.String, me.chyxion.lawnation.dao.PageParam)
	 */
	@Override
	public String getPreparedPageSQL(String strSQL,
			PageParam<?> pageParam) {
		return getPageSQL(strSQL, pageParam, true);
	}
}
